// 知识库引用 插件
<template>
  <el-dialog
    class="document-reply-dialog"
    :visible="visible"
    :title="$t('wiki.list.quote.title1')"
    @open="handleOpen"
    @close="handleClose"
  >
    <div class="search">
      <el-input v-model="searchParam.keyword"> </el-input>
      <el-button
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      ></el-button>
    </div>
    <div class="list" v-loading="loading">
      <div
        class="list-item"
        v-for="item in list"
        :key="item.id"
        @click="handleToggle(item)"
      >
        <div class="__checkbox">
          <el-checkbox
            v-model="item.checked"
            @change="handleUpdate(item)"
          ></el-checkbox>
        </div>
        <div class="__content">
          <div class="item-top">
            <h3>
              <p class="item-title" ref="title" v-html="item.handleTitle">
                {{ item.title }}
              </p>
              <div class="type" v-if="item.label && item.label.length > 0">
                <!-- @click="handleTags(tag)" -->
                <el-tag
                  class="search-tag"
                  v-for="(tag, index) in (item.label || []).slice(0, 5)"
                  :key="index"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </h3>
            <!-- 草稿箱显示审核状态 -->
            <el-tag
              class="review-tag"
              v-if="item.examineState && item.examineState != 0"
              :type="item.examineState == 1 ? '' : 'danger'"
            >
              {{ item.examineState == 1 ? $t('wiki.list.quote.des1') : $t('wiki.list.quote.des2') }}
            </el-tag>
          </div>

          <div class="item-cursor">
            <div class="item-info">
              <span class="name">
                <template v-if="isOpenData">
                  <open-data
                    type="userName"
                    :openid="item.createUserStaffId"
                  ></open-data>
                </template>
                <template v-else>
                  {{ item.createUserName }}
                </template>
              </span>
              <span class="time">
                {{$t('wiki.list.quote.des3')}}：{{ item.createtime | fmt_datehour }}
              </span>
              <!-- <span class="type">{{item.type}}</span> -->
            </div>

            <p class="item-content" ref="content" v-html="item.handleContent">
              {{ item.content }}
            </p>
          </div>
        </div>
      </div>
      <div v-show="!list.length" class="list-empty" v-loading="loading">
        <img class="empty-img" :src="noDataImage" />
        <span class="empty-msg">{{$t('common.base.tip.noData')}}</span>
      </div>
    </div>
    <el-pagination
      class="list-pagination"
      background
      @current-change="handleJump"
      @size-change="handleSizeChange"
      :page-sizes="defaultTableData.defaultPageSizes"
      :page-size="searchParam.pageSize"
      :current-page="searchParam.pageNum"
      :pager-count="5"
      small
      layout="prev, pager, next, sizes, jumper"
      :total="listTotal"
    >
    </el-pagination>
    <template #footer>
      <!-- current-page 当前页面 -->
      <div class="footer">
        <el-button type="primary" @click="handleSave">{{$t('common.base.save')}}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import * as RepositoryApi from '@src/api/Repository';
import { getOssUrl } from '@src/util/assets'
import { defaultTableData } from '@src/util/table'
const noDataImage = getOssUrl('/no_data.png')

export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    allowShare: {
      type: Number,
      default: 1,
    }
  },
  data() {
    return {
      defaultTableData,
      noDataImage,
      loading: false,
      list: [],
      checkedMap: new Map(), // 选中的列表
      listTotal: 0,
      searchParam: {
        pageNum: 1,
        pageSize: 10,
        keyword: '',
        view: 'published',
        allowShare: 1,
      },
    };
  },
  beforeMount(){
    this.searchParam.allowShare = this.allowShare;
  },
  methods: {
    /**
     * 打开弹窗
     */
    handleOpen() {
      this.checkedMap = new Map([]); // 初始选中列表
      this.resetSearchParams();
      this.handleSearch();
    },
    resetSearchParams() {
      this.searchParam.pageNum = 1;
      this.searchParam.keyword = '';
    },
    /**
     * 关闭弹窗
     */
    handleClose() {
      this.$emit('update:visible', false);
    },
    dealData(res) {
      const { list, total } = res.result;
      this.listTotal = total;

      this.list = list.map(item => {
        item.checked = this.checkedMap.has(item.id); // 勾选状态
        if (typeof item.label === 'string') {
          item.label = item.label ? JSON.parse(item.label) : [];
        }

        if (item.title.indexOf('<em>') != -1) {
          let replaceReg = new RegExp('<em>', 'g');
          item.handleTitle = item.title.replace(
            replaceReg,
            '<span style="color: #FF7B00">'
          );
          let reg = new RegExp('</em>', 'g');
          item.handleTitle = item.handleTitle.replace(reg, '</span>');
        } else {
          item.handleTitle = item.title;
        }

        if (item.content.indexOf('<em>') != -1) {
          let replaceReg = new RegExp('<em>', 'g');
          item.handleContent = item.content.replace(
            replaceReg,
            '<span style="color: #FF7B00">'
          );
          let reg = new RegExp('</em>', 'g');
          item.handleContent = item.handleContent.replace(reg, '</span>');
        } else {
          item.handleContent = item.content;
        }
        return item;
      });
    },
    async requestList() {
      try {
        const res = await RepositoryApi.getDocumentList(this.searchParam);
        if (res.success) {
          this.dealData(res);
          return this.list;
        }
        this.$platform.notification({
          title: res.message,
          type: 'error',
        });
        this.dealData({
          list: [],
          total: 0,
        });

        return Promise.reject('request fail');
      } catch (error) {
        return Promise.reject('request fail', error);
      }
    },
    /**
     * 切换选中状态
     */
    handleToggle(item) {
      this.handleUpdate(item);
    },

    handleUpdate(item) {
      item.checked = !item.checked;
      if (item.checked) {
        this.checkedMap.set(item.id, item);
      } else {
        this.checkedMap.delete(item.id);
      }
    },

    async handleSearch() {
      try {
        if (this.loading) return;
        this.loading = true;
        await this.requestList();
      } finally {
        this.loading = false;
      }
    },

    /**
     * 切换pagesize
     */
    handleSizeChange(pageSize) {
      this.searchParam.pageNum = 1;
      this.searchParam.pageSize = pageSize;
      this.handleSearch();
    },
    /**
     * 切换page
     */
    handleJump(pageNum) {
      this.searchParam.pageNum = pageNum;
      this.handleSearch();
    },

    /**
     * 保存
     */
    handleSave() {
      this.$emit('choose', this.checkedMap); // 返回选中项
      this.handleClose();
    },
  },
};
</script>

<style lang="scss">
.document-reply-dialog {
  .el-dialog__body {
    padding: 20px 0;
  }
  .search {
    padding: 0 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .el-input {
      flex: 1;
      margin-right: 20px;
    }
  }
  .list {
    min-height: 30vh;
    max-height: 60vh;
    overflow-y: auto;
    padding: 20px 20px 0 20px;
    overflow-y: auto;

    .list-item {
      margin-bottom: 15px;
      cursor: pointer;
      padding: 5px;
      border-radius: 4px;
      box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
      display: flex;
      align-items: center;
      &:hover {
        background: rgba(204, 204, 204, 0.3);
      }
      .__checkbox {
        padding-right: 15px;
      }
      .__content {
        flex: 1;
      }
      .item-top {
        justify-content: space-between;
        h3 {
          display: flex;
          margin-bottom: 0;
          overflow: hidden;
          flex: 1;
          p {
            max-width: 50%;
          }
        }
        .search-tag {
          height: 22px;
          background: $color-primary-light-1;
          border-radius: 4px;
          border: 1px solid $color-primary-light-1;
          font-size: 12px;
          font-weight: 400;
          color: $color-primary-light-6;
          margin-left: 16px;
          & + .search-tag {
            margin-left: 4px;
          }
        }
      }
    }
  }
  .list-pagination {
    margin-top: 20px;
    padding: 0 20px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
  .list-empty {
    padding-top: 50px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    img {
      width: 160px;
    }
    .empty-msg {
      margin-top: 8px;
      font-size: $font-size-base;
      color: $text-color-regular;
    }
  }

  .footer {
    margin-top: 20px;
    padding: 0 20px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
}
</style>
